/**
 * @ClassName KP20_addTwoNumbers
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/10/14 19:45
 */

/**
 * 两数相加
 */
public class KP20_addTwoNumbers {

    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    /**
     * 链表从低位相加
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int len1 = listLength(l1);
        int len2 = listLength(l2);
        ListNode lNode = len1 >= len2 ? l1 : l2;
        ListNode sNode = lNode == l1 ? l2 : l1;
        int carryDevice = 0;
        ListNode pre = null;
        while (sNode != null) {
            int sum = lNode.val + sNode.val + carryDevice;
            lNode.val = sum % 10;
            carryDevice = sum / 10;
            pre = lNode;
            lNode = lNode.next;
            sNode = sNode.next;
        }
        while (lNode != null) {
            int sum = lNode.val + carryDevice;
            lNode.val = sum % 10;
            carryDevice = sum /10;
            pre = lNode;
            lNode = lNode.next;
        }
        if (carryDevice == 1) {
            ListNode node = new ListNode(1);
            pre.next = node;
        }
        return len1 >= len2 ? l1 : l2;
    }

    /**
     * 求链表长度
     * @param cur
     * @return
     */
    public int listLength(ListNode cur) {
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }
}
